<?php
require_once('Extension/Controller/Plugin/Abstract.php');

require_once('Extension/Auth/Storage/Session.php');

class Extension_Controller_Plugin_Web_Auth_DbTable extends Extension_Controller_Plugin_Abstract
{
    //public function routeStartup(Zend_Controller_Request_Abstract $request) {}
    //public function routeShutdown(Zend_Controller_Request_Abstract $request) {}

    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        self::initAuthDbTable($request);
    }

    //public function preDispatch(Zend_Controller_Request_Abstract $request) {}
    
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        self::redirectLogin($request);
    }
    
    //public function dispatchLoopShutdown() {}


    public static function initAuthDbTable(Zend_Controller_Request_Abstract $request)
    {
        $config = Kbs::initConfig('Auth/DbTable');

        if ($config->enable) {
            require_once('Zend/Auth.php');
            $auth = Zend_Auth::getInstance();

            $namespace = Kbs::initConfig('Session')->namespace->auth->dbTable;
            $storage = new Extension_Auth_Storage_Session($namespace);
            $auth->setStorage($storage);
        
            if (!Zend_Registry::isregistered('authAdapterDbTable')) {

                require_once('Zend/Auth/Adapter/DbTable.php');
                $authAdapterDbTable = new Zend_Auth_Adapter_DbTable( Kbs::initDb() );
                $authAdapterDbTable->setTableName($config->tableName);
                $authAdapterDbTable->setIdentityColumn($config->identityColumn);
                $authAdapterDbTable->setCredentialColumn($config->credentialColumn);
                $authAdapterDbTable->setCredentialTreatment($config->credentialTreatment);
                Zend_Registry::set('authAdapterDbTable', $authAdapterDbTable);
                return $authAdapterDbTable;

            } else {
                return Zend_Registry::get('authAdapterDbTable');
            }
        } else {
            return false;
        }
    }

    public static function redirectLogin(Zend_Controller_Request_Abstract $request)
    {
        $config = Kbs::initConfig('Auth/DbTable');
        $uri = $request->getRequestUri();

        $auth = Zend_Auth::getInstance();

        $namespace = Kbs::initConfig('Session')->namespace->auth->dbTable;
        $storage = new Extension_Auth_Storage_Session($namespace);
        $auth->setStorage($storage);
            
        if (!$auth->hasIdentity() and $config->loginUri != $uri) {
            $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
            $redirector->gotoUrlAndExit($config->loginUri);
        }
    }


}